package com.wrial.kind.linkedList;
/*
 * @Author  Wrial
 * @Date Created in 18:12 2020/8/7
 * @Description  链表合并
 */

import java.util.List;

public class MergeTwoLists {

    /**
     *  两个有序链表合并
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode();
        ListNode p = dummy;
        while (l1 != null && l2 != null) {
            int minVal;
            if (l1.val < l2.val) {
                minVal = l1.val;
                l1 = l1.next;
            } else {
                minVal = l2.val;
                l2 = l2.next;
            }
            p.next = new ListNode(minVal);
            p = p.next;
        }
        if (l1 != null) {
            p.next = l1;
        }
        if (l2!=null){
            p.next = l2;
        }
        return dummy.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
